<!-- 首页 -->
<template>
	<div>
		<!-- 使用首页的头部组件 -->
		<HomeHeader></HomeHeader>
		<!-- 使用轮播图组件 -->
		<HomeSwiper :list="swiper"></HomeSwiper>
		<!-- 使用图标组件 -->
		<HomeIcons :list='icon'></HomeIcons>
		<!-- 使用推荐区域组件 -->
		<HomeRecommend :list='recommend'></HomeRecommend>
		<!-- 使用周末推荐 -->
		<HomeWeekend :list='weekend'></HomeWeekend>
	</div>
</template>

<script>
	/* 引入头部组件 */
	import HomeHeader from './components/Header.vue';
	/* 引入轮播图组件 */
	import HomeSwiper from './components/Swiper.vue';
	/* 引入图标组件 */
	import HomeIcons from './components/Icons.vue';
	/* 引入推荐区域组件 */
	import HomeRecommend from './components/Recommend.vue';
	/* 引入周末推荐区域组件 */
	import HomeWeekend from './components/Weekend.vue';
	/* 引入axios第三方ajax包 */
	import axios from 'axios';
	/* 引入vuex */
	import {
		mapState
	} from 'vuex'
	export default {
		name: 'home',
		components: {
			/* 注册组件 */
			HomeHeader: HomeHeader,
			HomeSwiper: HomeSwiper,
			HomeIcons: HomeIcons,
			HomeRecommend: HomeRecommend,
			HomeWeekend: HomeWeekend
		},
		data() {
			return {
				lastCtiy: '',
				swiper: [],
				icon: [],
				recommend: [],
				weekend: []
			}
		},
		computed: {
			...mapState(['city'])
		},
		methods: {
			/* 获取城市列表去/json */
			getHomeCity() {
				return axios.get('/api/city.json');
			},
			/* 获取图片json */
			getHomePicture() {
				return axios.get('/api/index.json?city=' + this.city)
			},
			/* 发送ajax请求 */
			getHomeInfo() {
				const _this = this;
				/* 同时发送多个请求 */
				axios.all([this.getHomeCity(), this.getHomePicture()])
					.then(axios.spread(function(city, picture) {
						// 两个请求现在都执行完成
						_this.getHomeScc(city, picture)
					}));
			},
			/* 请求完成 */
			getHomeScc(city, picture) {
				// city = city.data;
				picture = picture.data;
				/* 获取返回的数据 */
				// city.data.hotCities.forEach(e => this.city = e.name);
				this.swiper = picture.data.swiperList;
				this.icon = picture.data.iconList;
				this.recommend = picture.data.recommendList;
				this.weekend = picture.data.weekendList;
			}
		},
		mounted() {
			// 保存上一次请求的城市数据
			this.lastCtiy = this.city;
			/* 当模板渲染完毕挂载到页面时调用该函数 */
			this.getHomeInfo();
		},
		// 当时用了keep-alive时，就会多一个该生命周期函数
		// 	当每次加载缓存中的数据后，就会触发该函数
		activated() {
			/*
			这里判断新数据和上次数据是否一致
				否就重新的发送该页请求
				是就继续调用缓存中的数据
			*/
			if (this.lastCtiy !== this.city) {
				this.lastCtiy = this.city;
				this.getHomeInfo;
			}
		}
	}
</script>

<style>

</style>
